package com.tony.mulitithread.utils;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.ReentrantLock;

public class AsyncTaskUtil {

    private volatile static ThreadPoolExecutor executor;

    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 获取线程池
     * @return
     */
    private static ThreadPoolExecutor getThreadPoolExecutor(){
        if (executor == null){
            LOCK.lock();
            try {
                if (executor == null){
                    executor = (ThreadPoolExecutor)SpringContextHelper.getBean("ScmThreadPoolExecutor");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                LOCK.unlock();
            }
        }
        return executor;
    }

    public static void asyncTask(Object object,String methodName,Object[] args){
        AsyncTask asyncTask = new AsyncTask(object, methodName, args);
        asyncTask(asyncTask);
    }

    public static void asyncTask(Runnable asyncTask){
        AsyncTaskUtil.getThreadPoolExecutor().execute(asyncTask);
    }

    public static <T> Future<T> asyncTask(Callable<T> callableTask){
        return AsyncTaskUtil.getThreadPoolExecutor().submit(callableTask);
    }
}
